import router from "@/router"
import store from '@/store'

import { Loading,Message } from 'element-ui';
const recursion = (list,val)=>{
    let str = false
    for(let v of list){
        // console.log(v.path,"%%%",val);
        if(v.path==val){
            str = true;
            break;
        }else if(!str){
            str = recursion(v.child,val)
        }
    }
    // console.log("QWQ",str);
    return str;
}
export default {
    data:{
        // baseURL: 'https://api.lovepurethai.com/',
        baseURL: process.env.NODE_ENV === "development"?'https://chuntai.shanghaijiudao.com/':'https://chuntai.shanghaijiudao.com/',
    },
    derive(url,param={},parameter=""){//导出
        var a = document.createElement("a");
        a.target="view_window";
        if(!parameter){
            for(let key in param){
                parameter+=`${key}=${param[key]}&`
            }
        }
        a.href = this.data.baseURL +`${url}?${parameter}`;
        // window.open(this.data.baseURL +`${url}?${parameter}`,"","width=100,height=100")
        a.click();
    },
    downloadXlsx(blob,name=""){//下载 表格.xlsx
        if(!blob)return;
        var reader = new FileReader()
        reader.addEventListener('loadend', (e)=> {
            console.log(blob.type,'blob.type',e);
            // if(blob.type === 'application/json'){
            try {
                let {code,msg} = JSON.parse(e.target.result);
                Message.error(msg);
                return;
            } catch (error) {
                var downloadUrl = window.URL.createObjectURL(new Blob([blob]));//转换
                var anchor = document.createElement("a");
                anchor.href = downloadUrl;
                // 生成时间戳
                let date = new Date();
                let timestamp = this.time(date,true);
                anchor.download = decodeURI(name+timestamp+'.xls');
                anchor.click();
            }
        })
        reader.readAsText(blob)
    },
    //十六进制Hex转RGB
    hexToRgb(sColor, str = true) {
        let reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
        sColor = sColor.toLowerCase();
        if (sColor && reg.test(sColor)) {
            if (sColor.length === 4) {
                let sColorNew = "#";
                for (let i = 1; i < 4; i += 1) {
                    sColorNew += sColor.slice(i, i + 1).concat(sColor.slice(i, i + 1));
                }
                sColor = sColorNew;
            }
            //处理六位的颜色值
            let sColorChange = [];
            for (let i = 1; i < 7; i += 2) {
                sColorChange.push(parseInt("0x" + sColor.slice(i, i + 2)));
            }
            if(!str) {
                return sColorChange;
            } else {
                return `rgb(${sColorChange[0]},${sColorChange[1]},${sColorChange[2]})`;
            }
        } else if (/^(rgb|RGB)/.test(sColor)) {
            let arr = sColor.replace(/(?:\(|\)|rgb|RGB)*/g, "").split(",")
            return arr.map(val => Number(val));
        } else {
            return sColor;
        }
    },
    readJson(){
        // 定义JSON数据
        let data = { "name": "小明" };
        // 转换成字符串数组
        let string = JSON.stringify(data);
        // 转换成Blob类型数据
        let blobData = new Blob([string]);
        console.log(blobData) // 打印Blob结果： Blob { size: 17, type: "" }
        let reader = new FileReader(); // 创建读取文件对象
        reader.addEventListener("loadend", function () { // 
            let res = JSON.parse(reader.result); // 返回的数据
            console.log(res,'返回结果数据') // { name: "小明" }
        });
        reader.readAsText(blobData, 'utf-8'); // 设置读取的数据以及返回的数据类型为utf-8
    },
    goUrl:(url)=>{
        if(url){
            router.push({path:url})
        }else{
            that.$message.error('路由参数错误')
        }
    },
    goNew(url){
        if(!url||url=="#")return;
        window.open(url);
    },
	backPage(index=-1){
		router.go(index)
    },
    jurisdictionJudge(val){
        let menuList = store.state.settings.menuList;
        // let path = thas.$route.path,str=false;
        console.log(recursion,"@#!@$@");
        return recursion(menuList,val);
    },
    dateStartEnd (dtStart,dtEnd,type=false) {//计算时间差
        var date1=new Date(`2016/1/1 ${dtStart}`);    //开始时间
        var date2=new Date(`2016/1/${type?2:1} ${dtEnd}`);    //结束时间
        var date3=date2.getTime() - date1.getTime(); //时间差秒
        // console.log(date1,'----',date2);
        //计算出相差天数
        // var days=Math.floor(date3/(24*3600*1000));

        //计算出小时数
        var leave1=date3%(24*3600*1000)  ;  //计算天数后剩余的毫秒数
        var hours=leave1/(3600*1000);
        console.log(hours,'leave1/(3600*1000)');

        //计算相差分钟数
        // var leave2=leave1%(3600*1000);        //计算小时数后剩余的毫秒数
        // var minutes=Math.floor(leave2/(100*1000));

        // //计算相差秒数
        // var leave3=leave2%(60*1000) ;     //计算分钟数后剩余的毫秒数
        // var seconds=Math.round(leave3/1000);
        return hours;
    },
	isLoadding(flag){
		if(flag) {
		  Loading.service({ fullscreen: true });
		}else{
		  (Loading.service({ fullscreen: true })).close();
		}
    },
    message(message,type="suc"){
        switch (type) {
            case 'suc':
            Message({ showClose: true, message, type: 'success' });
            break;
            case 'war':
            Message({ showClose: true, message, type: 'warning' });
            break;
            case 'err':
            Message({ showClose: true, message, type: 'error' });
            break;
            case 'info':
            Message({ showClose: true, message, type: 'info' });
            break;
        }
    },
	/**
	 * @param {Object} arr 数组
	 * @param {Object} name 字段名
	 * 数组提取某个元素名并拼接成一个新数组返回
	 */
	arrGetName(arr,owName,str){
		if(arr.length > 0){
			var newArr = [];
			arr.forEach((a,i)=>{
				newArr.push(a[owName]);
			})
			if(str != ''){
				newArr = newArr.join(str);
			}
			return newArr;
		}else{
			return false;
		}
	},
	/**
	 * @param {Object} arr 数组
	 * @param {Object} newArrLength 要拆分的每个数量
	 * 数组拆分
	 */
	changeArrGroup(arr, newArrLength) {
		let changeIndex = 0;
		let secondArr = [];
		while (changeIndex < arr.length) {
			secondArr.push(arr.slice(changeIndex, changeIndex += newArrLength))
		}
		return secondArr;
	},
	//key(需要检索的键） url（传入的需要分割的url地址，例：?id=2&age=18）
	getSearch(key, Url) {
		var str = Url;
		str = str.substring(1, str.length); // 获取URL中?之后的字符（去掉第一位的问号）
		// 以&分隔字符串，获得类似name=xiaoli这样的元素数组
		var arr = str.split("&");
		var obj = new Object();
		// 将每一个数组元素以=分隔并赋给obj对象
		for (var i = 0; i < arr.length; i++) {
			var tmp_arr = arr[i].split("=");
			obj[decodeURIComponent(tmp_arr[0])] = decodeURIComponent(tmp_arr[1]);
		}
		return obj[key];
	},
	/**
	 * 判断是否是微信环境
	 */
	isWX() {
		var ua = navigator.userAgent.toLowerCase();
		if (ua.match(/MicroMessenger/i) == "micromessenger") {
			return true;
		}
		return false;
	},
	/**
	 * @param [{Object}] 数组对象
	 * @param {String} str 给定字符
	 * 对象中的null或者空字符串转换为 给定的字符
	 */
	objNull2String(arr, str = '-') {
		if (arr.length > 0) {
			var resArr = [];
			arr.forEach((a, i) => {
				let resParams = {};
				Object.keys(a).forEach(key => {
					if (a[key] === '' || a[key] === null) { //判断参数不为空字符串
						resParams[key] = str;
					} else {
						resParams[key] = a[key];
					}
				});
				resArr.push(resParams);
			})
			console.log(resArr);
			return resArr;
		}
		return arr;
	},
	/**
	 * @param {Object} fmt
	 * @param {Object} date
	 * 时间格式化
	 */
	dateFormat(fmt, date) {
		if (date instanceof Date && !isNaN(date.getTime())) {
			let ret;
			let opt = {
				"Y+": date.getFullYear().toString(), // 年
				"m+": (date.getMonth() + 1).toString(), // 月
				"d+": date.getDate().toString(), // 日
				"H+": date.getHours().toString(), // 时
				"M+": date.getMinutes().toString(), // 分
				"S+": date.getSeconds().toString() // 秒
			};
			for (let k in opt) {
				ret = new RegExp("(" + k + ")").exec(fmt);
				if (ret) {
					fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
				};
			};
			console.log(111111111111);
			return fmt;
		} else {
			console.log(222222222222);
			return '-';
		}

	},
	/**--------------获取cookies--------------**/
	getCookie(name) {
		let arr,
			reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
		if ((arr = document.cookie.match(reg))) return arr[2];
		else return null;
	},
    time(date,type) {
        var y = date.getFullYear()
        var m = date.getMonth() + 1
        m = m < 10 ? '0' + m : m
        var d = date.getDate()
        d = d < 10 ? '0' + d : d
        var h = date.getHours()
        h = h < 10 ? '0' + h : h
        var minute = date.getMinutes()
        minute = minute < 10 ? '0' + minute : minute
        var second = date.getSeconds()
        second = second < 10 ? '0' + second : second
		if(type){
           return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + second
		}else{
			return y + '-' + m + '-' + d 
		}
    },
	
	timeMonth(date) {
        var y = date.getFullYear()
        var m = date.getMonth() + 1
        m = m < 10 ? '0' + m : m
        var d = date.getDate()
        d = d < 10 ? '0' + d : d
        var h = date.getHours()
        h = h < 10 ? '0' + h : h
        var minute = date.getMinutes()
        minute = minute < 10 ? '0' + minute : minute
        var second = date.getSeconds()
        second = second < 10 ? '0' + second : second
        // return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + second
        return y + '-' + m
    },
	/**--------------设置cookies--------------**/
	setCookie(c_name, value, expiredays) {
		let exdate = new Date();
		exdate.setDate(exdate.getDate() + expiredays);
		document.cookie =
			c_name +
			"=" +
			value +
			(expiredays == null ? "" : ";expires=" + exdate.toGMTString());
	},

	/**--------------删除cookies--------------**/
	delCookie(name) {
		let exp = new Date();
		exp.setTime(exp.getTime() - 1);
		let cval = getCookie(name);
		if (cval != null)
			document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();
	},

	/**--------------sessionStorage获取对象--------------**/
	getSession(key, isObj = true) {
		let value = sessionStorage.getItem(key);
		if (isObj) {
			value = JSON.parse(value);
		}
		return value;
	},

	/**--------------sessionStorage设置对象--------------**/
	setSession(key, value) {
		let str = value;
		if (value !== undefined && typeof value === "object") {
			str = JSON.stringify(value);
		}
		sessionStorage.setItem(key, str);
	},

	/**--------------sessionStorage删除对象--------------**/
	delSession(key) {
		sessionStorage.removeItem(key);
	},

	/*-----------------手机号隐藏中间4位-------------------*/
	hidePhoneNum(phone) {
		let result = "";
		if (phone != null) {
			result = phone.substring(0, 3) + "****" + phone.substring(7);
		}
		return result;
	},

	/*---------------------获取当前最新时间----------------------*/
	getNowDate(date,isDay) {
		var y = date.getFullYear();
		var m = date.getMonth() + 1;
		m = m < 10 ? "0" + m : m;
		var d = date.getDate();
		d = d < 10 ? "0" + d : d;
		var h = date.getHours();
		h = h < 10 ? "0" + h : h;
		var minute = date.getMinutes();
		minute = minute < 10 ? "0" + minute : minute;
		var second = date.getSeconds();
		second = second < 10 ? "0" + second : second;
		if(isDay){
			return y + "-" + m + "-" + d
		}else{
		    return y + "-" + m + "-" + d + " " + h + ":" + minute + ":" + second;
		}
	},

	/**----------------- 数字转换金额------------------ ***/
	numberToAmount(num, n = 2) {
		if (!num && num !== 0) {
			return "";
		}
		if (!isNaN(num)) {
			num = parseFloat(num).toFixed(n);
		} else {
			num = num;
		}
		var re = /(\d{1,3})(?=(\d{3})+(?:\.))/g;
		return num.replace(re, "$1,");
	},

	/**-------------------------- 金额转换数字----------------------**/
	amountToNumber(value) {
		let num = value;
		if (!num) {
			return "";
		}
		num = num.toString();
		num = num.replace(/[ ]/g, "");
		num = num.replace(/,/gi, "");
		if (!isNaN(num)) {
			return Number(num);
		}
		return num;
	},
	/**-------------------------- 字符串转数字且保留两位有效小数----------------------**/
	stringToNumber(val) {
		if (!val) {
			return "";
		}
		val = val.replace(/[ ]/g, "");
		val = val.replace(/,/gi, "");
		if (!isNaN(val)) {
			return parseFloat(val).toFixed(2);
		}
		return val;
	},
	/**--------------检查上传文件的大小--------------**/
	checkFileSize(file, size = 10) {
		if (file.size > size * 1024 * 1024) {
			MessageBox.confirm(`文件大小不能超过${size}MB`, {
				confirmButtonText: "知道了",
				type: "warning",
				showCancelButton: false,
				showClose: false
			});
			return false;
		}
		return true;
	},
	/**--------------日期转化--------------**/
	dateFormatter(value, fmt = "yyyy-MM-dd hh:mm:ss") {
		if (!value) {
			return "";
		}
		let date = new Date(Number(value));
		let o = {
			"M+": date.getMonth() + 1, //月份
			"d+": date.getDate(), //日
			"h+": date.getHours(), //小时
			"m+": date.getMinutes(), //分
			"s+": date.getSeconds(), //秒
			"q+": Math.floor((date.getMonth() + 3) / 3), //季度
			S: date.getMilliseconds() //毫秒
		};
		if (/(y+)/.test(fmt))
			fmt = fmt.replace(
				RegExp.$1,
				(date.getFullYear() + "").substr(4 - RegExp.$1.length)
			);
		for (var k in o)
			if (new RegExp("(" + k + ")").test(fmt))
				fmt = fmt.replace(
					RegExp.$1,
					RegExp.$1.length == 1 ?
					o[k] :
					("00" + o[k]).substr(("" + o[k]).length)
				);
		return fmt;
	},

	/**----------------超出字数显示省略号---------------------------**/
	overPartWord(value) {
		if (!value) {
			return "";
		}
		if (value.length > 10) {
			return value.substring(0, 10) + "...";
		}
		return value;
	},
	/**-------------------对象或数组深拷贝---------------------------**/
	objDeepCopy(source) {
		let sourceCopy = source instanceof Array ? [] : {};
		for (let item in source) {
			sourceCopy[item] =
				typeof source[item] === "object" && source[item] !== null ?
				this.objDeepCopy(source[item]) :
				source[item] === null ?
				"" :
				source[item];
		}
		return sourceCopy;
	},
	/**------保留n位小数(直接截取，不会四舍五入)-------**/
	pointTo(num, n = 2) {
		if (isNaN(num)) {
			return "";
		}
		if (!num && num !== 0) {
			return "";
		}
		if (num && num <= 0) {
			return "";
		}
		if (num.toString().indexOf(".") > -1) {
			let intp = num.toString().split(".")[0];
			let pp = num.toString().split(".")[1];
			if (pp.length > n) {
				pp = pp.substr(0, n);
			}
			return (num = Number(intp + "." + pp));
		} else {
			return (num = Number(num));
		}
	},
	// 判断是否是0-100的非负整数
	checkNonInt(num) {
		let reg = new RegExp("^(\\d|[1-9]\\d|100)$");
		return reg.test(num);
	},
	// 判断是否是整数
	checkInt(val, n = 15) {
		let flag = isNaN("" + val);
		if (flag) {
			return false;
		}
		let str = "^\\d{1," + n + "}$";
		let reg = new RegExp(str);
		return reg.test(val);
	},
	// 判断是否只有n位小数
	checkFloatNeg(val, n = 2) {
		let flag = isNaN("" + val);
		if (flag) {
			return false;
		}
		let str = "^-?[0-9]+(.\\d{1," + n + "})?$";
		let reg = new RegExp(str);
		return reg.test(val);
	},

	/**-------------将对象转成路由字符串参数--------------**/
	createPath(url, params = {}) {
		let urlParams = [];
		Object.keys(params).forEach(key => {
			if (params[key] != '') { //判断参数不为空字符串
				urlParams.push(`${key}=${encodeURIComponent(params[key])}`);
			}
		});
		if (urlParams.length) {
			urlParams = `${url}?${urlParams.join("&")}`;
		} else {
			urlParams = url;
		}
		return urlParams;
	},
	/**-------------------- 数组去重 ----------------------**/
	distinctArray(arr, key) {
		let result = [];
		let obj = {};
		for (var i = 0; i < arr.length; i++) {
			if (!obj[arr[i][key]]) {
				result.push(arr[i]);
				obj[arr[i][key]] = true;
			}
		}
		return result;
	},
	// json数组根据某一元素判重
	arrCheckKey(arr, key) {
		// var arr = [{ d: '2015-10-12',C:'Apple'}, { d: '2015-10-12',C:'Apple'}, { d: '2015-10-13',C :'Apple' }];
		var find = false;
		for (var i = 0; i < arr.length; i++) {
			for (var j = i + 1; j < arr.length; j++) {
				if (arr[i][key] == arr[j][key]) {
					find = true;
					break;
				}
			}
			if (find) break;
		}
		return find;
	},
	// 手机号校验
	isPhoneAvailable(poneNum) {
		let myreg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
		if (!myreg.test(poneNum)) {
			return false;
		} else {
			return true;
		}
	},
	// 邮箱校验
	isEmailAvailable(email) {
		let myreg = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/;
		if (!myreg.test(email)) {
			return false;
		} else {
			return true;
		}
	},
	//是否包含中文
	hasChinese(value) {
		let cnReg = /([\u4e00-\u9fa5]|[\u3000-\u303F]|[\uFF00-\uFF60])/g;
		let mat = value.match(cnReg);
		return mat;
	},
	/*--------------精确到小数点后两位,.后补0和.前补0-------------------------*/
	saveNumberTwo(num) {
		if ((!num && num != 0) || num == "") {
			return "";
		}
		if (!isNaN(num)) {
			num = parseFloat(num).toFixed(2);
		}
		num += "";
		num = num.replace(/[^0-9|\.]/g, ""); //清除字符串中的非数字非.字符

		if (/^0+/) {
			//清除字符串开头的0
			num = num.replace(/^0+/, "");
		}
		if (!/\./.test(num)) {
			//为整数字符串在末尾添加.00
			num += ".00";
		}
		if (/^\./.test(num)) {
			//字符以.开头时,在开头添加0
			num = "0" + num;
			num += "00"; //在字符串末尾补零
			num = num.match(/\d+\.\d{2}/)[0];
		}
		return num;
	},
	//校验是否为纯数字
	isNum(str) {
		if (/^[0-9]+$/.test(str)) {
			//这是用正则表达是检查
			return true;
		}
		return false;
	},
	// 判断字符串是否为数字和字母组合
	checkS(str) {
		var zg = /^[0-9a-zA-Z]*$/;
		if (!zg.test(str)) {
			return false;
		} else {
			return true;
		}
	},
	//对象深拷贝
	deepClone(source) {
		if (!source && typeof source !== "object") {
			throw new Error("error arguments", "shallowClone");
		}
		const targetObj = source.constructor === Array ? [] : {};
		Object.keys(source).forEach(keys => {
			if (source[keys] && typeof source[keys] === "object") {
				targetObj[keys] = deepClone(source[keys]);
			} else {
				targetObj[keys] = source[keys];
			}
		});
		return targetObj;
	},
	clearCookie() {
		var keys = document.cookie.match(/[^ =;]+(?=\=)/g);
		if (keys) {
			for (var i = keys.length; i--;)
				document.cookie = keys[i] + "=0;expires=" + new Date(0).toUTCString();
		}
	},
	//清除所有cookie
	clearCookie() {
		var keys = document.cookie.match(/[^ =;]+(?=\=)/g);
		if (keys) {
			for (var i = keys.length; i--;)
				document.cookie = keys[i] + "=0;expires=" + new Date(0).toUTCString();
		}
	},
	//电话号码脱敏 头三尾三，其余*
	phoneJoinStart(value) {
		let str = value + "",
			first = "",
			last = "",
			start = "";
		if (str.length < 6) return str;
		first = str.substr(0, 3);
		last = str.substr(-3);
		for (let i = 0; i < str.length - 6; i++) {
			start += "*";
		}
		return first + start + last;
	},
	//证件号脱敏 前五其余*
	pIdJoinStart(value) {
		let str = value + "",
			first = "",
			start = "";
		if (str.length < 6) return str;
		first = str.substr(0, 5);
		for (let i = 0; i < str.length - 5; i++) {
			start += "*";
		}
		return first + start;
	},
	//判断是不是图片文件
	isImg(value) {
		return (/\.(gif|jpg|jpeg|png|GIF|JPG|PNG)$/.test(value))
	}
};
